﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Common.Logging;
using System.Reflection;

namespace DotNetNexusSpam
{
    /// <summary>
    /// Loads all domain that the engine will be watching.
    /// If 'domainToWatch.txt' is empty, all emails will be watched/filtered.
    /// </summary>
    public class DomainToWatch
    {
        private ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private const string DOMAIN_LIST = "domainToWatch.txt";
        private string[] _blacklist;
        private bool _isEmpty;
        public bool IsEmpty
        {
            get { return _isEmpty; }
            set { _isEmpty = value; }
        }

        public string[] LoadDomainList(string startupPath)
        {
            string configPath = startupPath + "config\\" + DOMAIN_LIST;
            if (File.Exists(configPath))
            {
                string blackListContent = "";
                using (StreamReader settingsReader = new StreamReader(configPath))
                {
                    blackListContent = settingsReader.ReadToEnd();
                }
                _blacklist = blackListContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                _log.Debug("DomainToWatchlist file was loaded succesfully.");
            }
            else
            {
                _log.Warn("DomainToWatchlist file could not be loaded from " + configPath);
            }

            if (_blacklist != null && _blacklist.Length > 0)
            {
                bool hasValidElements = false;
                foreach (string domainElement in _blacklist)
                {
                    if (domainElement.Trim() != "")
                    {
                        hasValidElements = true;
                        break;
                    }
                }
                if (hasValidElements)
                    _isEmpty = false;
                else
                    _isEmpty = true;
            }
            else
                _isEmpty = true;
            return _blacklist;
        }
    }
}
